package net.shopxx.action.shop;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import net.shopxx.bean.Pager;
import net.shopxx.entity.Member;
import net.shopxx.entity.MemberFavoriteProduct;
import net.shopxx.entity.Product;
import net.shopxx.entity.ProductCategory;
import net.shopxx.service.MemberFavoriteProductService;
import net.shopxx.service.MemberService;
import net.shopxx.service.ProductCategoryService;
import net.shopxx.service.ProductService;

import org.apache.struts2.convention.annotation.ParentPackage;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.opensymphony.xwork2.interceptor.annotations.InputConfig;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

/**
 * 前台Action类 - 收藏夹
 * ============================================================================
 */

@ParentPackage("shop")
public class MemberFavoriteProductAction extends BaseShopAction {

	private static final long serialVersionUID = 6297956848773319710L;
	
	private static final Integer pageSize = 8;// 商品收藏每页显示数
	
	private Product product;
	
	private String isToday="0" ;
	
	private MemberFavoriteProduct memberFavoriteProduct;
	
	private Member member;
	
	private String memberId;

	@Resource
	private MemberService memberService;
	@Resource
	private ProductService productService;
	
	@Resource
	private ProductCategoryService productCategoryService;
	
	@Resource
	private MemberFavoriteProductService memberFavoriteProductService;
	
	Map<String, String> jsonMap = new HashMap<String, String>();
	
	private List<ProductCategory> productCategoryList;

	// 商品收藏列表
	public String list() {
		
		
		SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd");
		
		
//		Member loginMember = getLoginMember();
		
		//获取所有分类信息
		productCategoryList=productCategoryService.getAll();
		
		if(id==null||id.trim().equals("")){
			id=productCategoryList.get(0).getId();
		}
		
		Member loginMember = memberService.load(memberId);
		
		//获取分类下的信息
		for(int i=0;i<productCategoryList.size();i++){
			DetachedCriteria detachedCriteria1 = DetachedCriteria.forClass(MemberFavoriteProduct.class);
			
			
			if(isToday==null||isToday.trim().equals("")){
				isToday="0";
			}
			else{
				if(isToday.trim().equals("1")) ;
				else
				 isToday="0";
			}
			
			if(isToday.equals("1")){
				try {
					detachedCriteria1.add(Restrictions.gt("createDate", sdf.parse(sdf.format(new Date()))));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
				}
			}
			else{
				try {
					detachedCriteria1.add(Restrictions.lt("createDate", sdf.parse(sdf.format(new Date()))));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
				}
				
			}
			
			detachedCriteria1.add(Restrictions.eq("productCategory", productCategoryList.get(i)));
			detachedCriteria1.add(Restrictions.eq("member", loginMember));
			detachedCriteria1.addOrder(Order.desc("createDate"));
			
			pager = memberFavoriteProductService.findByPager(pager, detachedCriteria1);
			
			jsonMap.put(productCategoryList.get(i).getId(), pager.getTotalCount().toString());
			
			
			
		}
		
		ProductCategory productCategory=productCategoryService.get(id);
		
		
		if (pager == null) {
			pager = new Pager();
		}
		pager.setPageSize(pageSize);
		
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(MemberFavoriteProduct.class);
		
		if(isToday.equals("1")){
			try {
				detachedCriteria.add(Restrictions.gt("createDate", sdf.parse(sdf.format(new Date()))));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
		}
		else{
			try {
				detachedCriteria.add(Restrictions.lt("createDate", sdf.parse(sdf.format(new Date()))));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
			
		}
		
		detachedCriteria.add(Restrictions.eq("productCategory", productCategory));
		detachedCriteria.add(Restrictions.eq("member", loginMember));
		
		
		
		
		detachedCriteria.addOrder(Order.desc("createDate"));
		
		pager = memberFavoriteProductService.findByPager(pager, detachedCriteria);
		return LIST;
	}

	// 添加收藏商品
	@Validations(
		requiredStrings = { 
			@RequiredStringValidator(fieldName = "id", message = "ID不允许为空!")
		}
	)
	@InputConfig(resultName = "error")
	public String ajaxAdd() {
		product = productService.load(id);
		if (!product.getIsMarketable()) {
			return ajaxJsonErrorMessage("此商品已下架!");
		}
		Member loginMember = getLoginMember();
		Set<Product> favoriteProductSet = (loginMember.getFavoriteProductSet() == null ? new HashSet<Product>() : loginMember.getFavoriteProductSet());
		if (favoriteProductSet.contains(product)) {
			return ajaxJsonWarnMessage("您已经收藏过此商品!");
		} else {
			favoriteProductSet.add(product);
			memberService.update(loginMember);
			return ajaxJsonSuccessMessage("商品收藏成功!");
		}
	}
	
	@InputConfig(resultName = "error")
	public String add() {
		//member=memberService.load(memberId);
		memberFavoriteProduct=new MemberFavoriteProduct();
		product = productService.get(id);
		
		if (!product.getIsMarketable()) {
			//return ajaxJsonErrorMessage("此商品已下架!");
			jsonMap.put(STATUS, ERROR);
			jsonMap.put(MESSAGE, "此商品已下架!");
			
			getResponse().setContentType("text/xml;charset=UTF-8");    
			return "message";
		}
//		Member loginMember = getLoginMember();
		
		Member loginMember = memberService.get(memberId);
		
		
		//查找收藏产品列表
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(MemberFavoriteProduct.class);
		detachedCriteria.add(Restrictions.eq("member", loginMember));
		detachedCriteria.add(Restrictions.eq("product", product));
		pager = memberFavoriteProductService.findByPager(pager, detachedCriteria);
		
		if(pager.getList()!=null&&pager.getList().size()>0){
			jsonMap.put(STATUS, ERROR);
			jsonMap.put(MESSAGE, "该商品已经收藏!");
			
			getResponse().setContentType("text/xml;charset=UTF-8");    
			return "message";
			
			
		}
		
		memberFavoriteProduct.setProduct(product);
		memberFavoriteProduct.setProductCategory(product.getProductCategory());
		memberFavoriteProduct.setMember(loginMember);
		memberFavoriteProductService.save(memberFavoriteProduct);
		
		
		
		
		jsonMap.put(STATUS, SUCCESS);
		jsonMap.put(MESSAGE, "商品收藏成功!");
		
		getResponse().setContentType("text/xml;charset=UTF-8");    
		return "message";
	}

	// 删除收藏商品
	public String delete () {
		try{
		memberFavoriteProduct = memberFavoriteProductService.load(id);
//		Member loginMember = getLoginMember();
		
		
		Member loginMember = memberService.load(memberId);
		if(memberFavoriteProduct.getMember().equals(loginMember)){
			memberFavoriteProductService.delete(memberFavoriteProduct);
			
			jsonMap.put(STATUS, SUCCESS);
			jsonMap.put(MESSAGE, "删除成功!");
			
			getResponse().setContentType("text/xml;charset=UTF-8");    
			return "message";
		}
		else{
			jsonMap.put(STATUS, ERROR);
			jsonMap.put(MESSAGE, "删除失败，非本人操作!");
			
			getResponse().setContentType("text/xml;charset=UTF-8");    
			return "message";
		}
		}
		catch(Exception e){
			jsonMap.put(STATUS, ERROR);
			jsonMap.put(MESSAGE, "系统错误，删除失败!");
			
			getResponse().setContentType("text/xml;charset=UTF-8");    
			return "message";
		}
	}

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public String getMemberId() {
		return memberId;
	}

	public void setMemberId(String memberId) {
		this.memberId = memberId;
	}

	public Member getMember() {
		return member;
	}

	public void setMember(Member member) {
		this.member = member;
	}

	public Map<String, String> getJsonMap() {
		return jsonMap;
	}

	public void setJsonMap(Map<String, String> jsonMap) {
		this.jsonMap = jsonMap;
	}

	public MemberFavoriteProduct getMemberFavoriteProduct() {
		return memberFavoriteProduct;
	}

	public void setMemberFavoriteProduct(MemberFavoriteProduct memberFavoriteProduct) {
		this.memberFavoriteProduct = memberFavoriteProduct;
	}

	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public ProductService getProductService() {
		return productService;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public MemberFavoriteProductService getMemberFavoriteProductService() {
		return memberFavoriteProductService;
	}

	public void setMemberFavoriteProductService(
			MemberFavoriteProductService memberFavoriteProductService) {
		this.memberFavoriteProductService = memberFavoriteProductService;
	}

	public static Integer getPageSize() {
		return pageSize;
	}

	public List<ProductCategory> getProductCategoryList() {
		return productCategoryList;
	}

	public void setProductCategoryList(List<ProductCategory> productCategoryList) {
		this.productCategoryList = productCategoryList;
	}

	public String getIsToday() {
		return isToday;
	}

	public void setIsToday(String isToday) {
		this.isToday = isToday;
	}

}